package simulator.physengine;

import java.util.ArrayList;
import java.util.List;

public class Physengine
{
	private List<Updateable>	_updateList;
	private List<PhysObject>	_physList;

	private List<Updateable>	_removeUpdateable;
	private List<PhysObject>	_removePhysObj;

	public Physengine()
	{
		_updateList = new ArrayList<>();
		_physList = new ArrayList<>();

		_removeUpdateable = new ArrayList<>();
		_removePhysObj = new ArrayList<>();
	}

	public void performIteration(float dt)
	{
		try
		{
			//perform physics calculations
			int physobjects = _physList.size();
			for (int i = 0; i < physobjects; i++)
			{
				_physList.get(i).physUpdate(dt);
			}

			//perform updates for updateables
			int updateables = _updateList.size();
			for (int i = 0; i < updateables; i++)
			{
				_updateList.get(i).update(dt);
			}

			//perform updates for physobjects
			physobjects = _physList.size();
			for (int i = 0; i < physobjects; i++)
			{
				_physList.get(i).update(dt);
			}

			//remove stuff which should be removed
			int rmUpdateables = _removeUpdateable.size();
			for (int i = 0; i < rmUpdateables; i++)
			{
				Updateable u = _removeUpdateable.get(i);
				_updateList.remove(u);
			}

			int rmPhysObj = _removePhysObj.size();
			for (int i = 0; i < rmPhysObj; i++)
			{
				PhysObject u = _removePhysObj.get(i);
				_physList.remove(u);
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	public void add(Updateable u)
	{
		if (_updateList.contains(u)) throw new IllegalArgumentException("Tried to add updateable, but this updateable was already present");

		_updateList.add(u);
	}

	public void add(PhysObject o)
	{
		if (_physList.contains(o)) throw new IllegalArgumentException("Tried to add physobject, but this physobject was already present");

		//add((Updateable) o);

		_physList.add(o);
	}

	public void remove(Updateable u)
	{
		_removeUpdateable.add(u);
	}

	public void remove(PhysObject o)
	{
		_removePhysObj.add(o);
	}
}
